/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.filters;

import controllers.pipes.Persistence2SenderPipe;
import controllers.pipes.Reader2ValidatorPipe;
import controllers.pipes.Validator2PersistencePipe;
import dao.ArchiveDAO;
import dao.DocumentTypeDAO;
import dao.FranchiseDAO;
import dao.TraceStateDAO;
import entities.*;
import facade.facadeClass;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Sergio
 */
public final class PersistenceFilter extends Thread {

  private long lines = 0;
  private Archive archive;
  private TraceStateDAO traceStateDao;
  private Trace entityTrace;
  private TraceState entityTraceState;
  private FranchiseDAO franchiseDAO;
  private DocumentTypeDAO documentTypeDAO;
  private DocumentType entityDocumentType;
  private Franchise entityFranchise;
  private facadeClass fc;
  private String checkSum;

  public void setArchive(Archive archive) {
    this.archive = archive;
  }


  public void setLines(long lines) {
    this.lines = lines;
  }

  public PersistenceFilter() {
    super("PersistenceFilter");
    System.out.println("Starting thread: " + this);
  }

  @Override
  public void run() {
    try {
      Persistence2SenderPipe theOutQueueInstance = Persistence2SenderPipe.getInstance();
      Validator2PersistencePipe theInQueueInstance = Validator2PersistencePipe.getInstance();
      while (lines == 0) {
        Thread.sleep(200);//number of lines has not been initialized, wait some time.
      }
      for (int i = 0; i < lines;) {
        String currentWord = theInQueueInstance.getElement();//read from the pipe.
        if (currentWord == null) {
          System.out.println("There is nothing here!! PERSISTENCE");//nothing in the pipe. Wait.
        } else {
          //send to persistence
          i++;//go to the next element in the pipa
          Persist(currentWord, i);
          theOutQueueInstance.insertInto(currentWord);
        }
        Thread.sleep(200);//wait
      }
    } catch (InterruptedException e) {
      System.out.println("Child interrupted.");
    }
    System.out.println("Exiting (consumer persistence).");
  }

  public void Persist(String line, int count) {
    String[] tempTrace;
    String delimiter = "\\|";
    tempTrace = line.split(delimiter);
    if ("0".equals(tempTrace[0])){
      String[] tTrace = new String[9];
      for (int j = 0; j < tempTrace.length - 1; j++){
        System.out.println(tempTrace[j+1]);
        tTrace[j] = tempTrace[j+1];
      }
      persistValidOnDB(count, archive, tTrace);
    }
    else {
//      persistInvalid()...
    }
  }

  public boolean persistValidOnDB(int idTransaction, Archive archive, String[] tempTrace) {
    traceStateDao = new TraceStateDAO();
    franchiseDAO = new FranchiseDAO();
    documentTypeDAO = new DocumentTypeDAO();
    ArchiveDAO archiveDAO = new ArchiveDAO();

    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("satacreditoclientePU");
    EntityManager em;
    em = emf.createEntityManager();

    em.getTransaction().begin();

    archive = archiveDAO.searchByIdMongi(em, archive.getIdMongo());
    entityTraceState = traceStateDao.searchById(em, 1);
    entityDocumentType = documentTypeDAO.searchByName(em, tempTrace[0]);
    entityFranchise = new Franchise();
    entityFranchise.setDescription(tempTrace[5]);
    em.getTransaction().commit();

    fc = new facadeClass();
    entityTrace = new Trace(archive, checkSum, entityTraceState, entityFranchise,
            entityDocumentType, idTransaction, Integer.valueOf(tempTrace[1]),
            tempTrace[2], tempTrace[3], tempTrace[4], Long.valueOf(tempTrace[6]),
            tempTrace[7], tempTrace[8]);
    entityTrace.setArchivoIdMondo(archive.getIdMongo());
    fc.create(entityTrace);
    return true;
  }
}